package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Commodity;
import cn.wolfcode.trip.base.domain.CommodityForm;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.CommodityFormMapper;
import cn.wolfcode.trip.base.mapper.CommodityMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.service.ICommodityFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CommodityFormServiceImpl implements ICommodityFormService {
    @Autowired
    private CommodityFormMapper formMapper;
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private UserMapper userMapper;

    public void saveForm(Long commodityId, User user) {
        Commodity commodity = commodityMapper.selectByPrimaryKey(commodityId);
        User user1 = userMapper.selectByPrimaryKey(user.getId());
        if (commodity.getIntegral().compareTo(user1.getIntegral()) == 1){
            throw new RuntimeException("您的积分不够");
        }
        CommodityForm commodityForm = new CommodityForm();
        commodityForm.setCreatTime(new Date());
        commodityForm.setUser(user1);
        commodityForm.setCommodity(commodity);
        formMapper.insert(commodityForm);
        commodity.setSalesVolume(commodity.getSalesVolume()+1);
        commodityMapper.updateSalesVolume(commodity);
        user1.setIntegral(user1.getIntegral().subtract(commodity.getIntegral()));
        userMapper.updateIntegral(user1);
    }
}
